﻿using Mimas.Framework.Server.DomainObjects;
using Mimas.Framework.Shared.Data.CriteriaObjects;
using Mimas.Framework.Shared.Data.DataTransferObjects;
using Mimas.Framework.Server.DomainObjects.Mapping;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mimas.Core.Current;
using System.IO;
using System.ServiceModel;

namespace Mimas.Framework.Server.AdminManagement
{
  public static class FileManagementBL
  {
    public static FileArchiveDTO[] GetFiles(FileArchiveCO criteria)
    {
      List<FileArchiveDTO> result = new List<FileArchiveDTO>();

      using (MIMASEntities db = new MIMASEntities())
      {
        DbSet<FileArchive> FileArchiveSet = db.Set<FileArchive>();

        var Linq = from fa in FileArchiveSet select fa;

        if (criteria.FileArchiveIds != null && criteria.FileArchiveIds.Any())
          Linq = Linq.Where(x => criteria.FileArchiveIds.Contains(x.Id));

        var LinqResult = Linq.ToArray();
        if (LinqResult != null && LinqResult.Any())
        {
          result = FileArchiveMapping.Map(LinqResult).ToList();
          if (criteria.GetFile)
          {
            foreach (var item in result)
            {
              string filePath = Constants.CurrentApplicationPath + "\\" + Constants.FileArchivePath + "\\" + item.Path + "\\" + item.Guid + "." + item.Extension;
              if (File.Exists(filePath))
                item.File = File.ReadAllBytes(filePath);
            }
          }
        }
      }

      return result.ToArray();
    }

    public static FileArchiveDTO[] SaveFiles(FileArchiveDTO[] data)
    {
      List<FileArchiveDTO> result = new List<FileArchiveDTO>();

      using (MIMASEntities db = new MIMASEntities())
      {
        DbSet<FileArchive> FileArchiveSet = db.Set<FileArchive>();

        int[] Ids = data.Where(x => x.Id > 0).Select(x => x.Id).Distinct().ToArray();

        var Linq = (from fa in FileArchiveSet select fa);

        if (Ids != null && Ids.Any())
          Linq = Linq.Where(x => Ids.Contains(x.Id));

        var ResultLinq = Linq.ToArray();

        using (var transaction = db.Database.BeginTransaction())
        {
          foreach (var item in data)
          {
            if (item.Id == 0 && item.IsDeleted) continue;

            FileArchive newItem = null;

            if (ResultLinq != null && ResultLinq.Any(x => x.Id == item.Id))
              newItem = ResultLinq.FirstOrDefault(x => x.Id == item.Id);
            else
            {
              newItem = new FileArchive();
              FileArchiveSet.Add(newItem);
            }

            newItem = FileArchiveMapping.Map(item);
            if (string.IsNullOrEmpty(item.Guid)) item.Guid = Guid.NewGuid().ToString();
            db.SaveChanges();
            item.Id = newItem.Id;
            string filePath = Constants.CurrentApplicationPath + "\\" + Constants.FileArchivePath + "\\" + item.Path + "\\" + item.Guid + "." + item.Extension;
            try
            {
              if (!Directory.Exists(Constants.CurrentApplicationPath + "\\" + Constants.FileArchivePath))
                Directory.CreateDirectory(Constants.CurrentApplicationPath + "\\" + Constants.FileArchivePath);

              if (!Directory.Exists(Constants.CurrentApplicationPath + "\\" + Constants.FileArchivePath + "\\" + item.Path))
                Directory.CreateDirectory(Constants.CurrentApplicationPath + "\\" + Constants.FileArchivePath + "\\" + item.Path);

              if (File.Exists(filePath))
              {
                File.Delete(filePath);
                File.WriteAllBytes(filePath, item.File);
              }
            }
            catch
            {
              throw new FaultException(new FaultReason(filePath), new FaultCode("S0013"));
            }
            result.Add(item);
          }
          transaction.Commit();
        }
      }

      return result.ToArray();
    }
  }
}
